package com.unittec.drainage.provider.auth.controller;

import java.util.List;

import javax.validation.ValidationException;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.unittec.drainage.provider.auth.dto.LoginRevertInfo;
import com.unittec.drainage.provider.auth.dto.SysPermissionTree;
import com.unittec.drainage.provider.auth.service.LoginService;
import com.unittec.drainage.provider.auth.service.SysUserService;
import com.unittec.drainage.provider.auth.util.PermissionDataUtil;
import com.unittec.drainage.provider.log.Log;
import com.unittec.drainage.provider.scope.ThreadLocalScope;
import com.unittec.drainage.provider.utils.GenerateCodeUtil;
import com.unittec.drainage.provider.utils.ValidationUtils;
import com.unittec.drainage.sdk.auth.request.Req101702;
import com.unittec.drainage.sdk.auth.request.Req101703;
import com.unittec.drainage.sdk.auth.request.Req101704;
import com.unittec.drainage.sdk.auth.request.Req101705;
import com.unittec.drainage.sdk.auth.response.Res101702;
import com.unittec.drainage.sdk.auth.response.Res101703;
import com.unittec.drainage.sdk.auth.response.Res101704;
import com.unittec.drainage.sdk.auth.response.Res101705;
import com.unittec.drainage.sdk.log.enums.LogOperateEnum;
import com.unittec.drainage.sdk.log.enums.LogStatusEnum;
import com.unittec.drainage.sdk.root.domain.GatewayRequest;
import com.unittec.drainage.sdk.root.domain.Result;
import com.unittec.drainage.sdk.root.enums.BizCode;
import com.unittec.drainage.sdk.root.enums.BizCodeEnum;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @author Jason
 * @description 登录管理
 * @date 2019/11/14
 */
@RestController
@Api(tags = "登录管理")
public class LoginController {

    @Autowired
    Log log;

    @Autowired
    private LoginService loginService;

    @Autowired
    private SysUserService sysUserService;

    @RequestMapping(value = "/101702", method = RequestMethod.POST)
    @ApiOperation(value = "获取验证码", notes = "获取验证码")
    @ResponseBody
    public Result<Res101702> getSmsCode(@RequestBody GatewayRequest<Req101702> req) {
        log.debug(req, "getSmsCode {}  ", "begin");
        long startLogTime = System.currentTimeMillis();
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        String code = GenerateCodeUtil.getFourRandomNumber(6);
        String phone = null;
        try {
            ValidationUtils.validateEntityStr(req.getContent());
            phone = req.getContent().getPhone();
            bizCodeEnum = loginService.sendSmsCode(phone, code);
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            log.addOperateLog("101702", JSON.toJSONString(req), "获取验证码",
                "手机号码：" + phone + "获取验证码失败：" + log.buildErrmsg(e), LogOperateEnum.LOG_OTHER.getCode(),
                LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, e.getMessage());
        }
        log.debug(req, "getSmsCode {}  ", "end");
        if (bizCodeEnum == BizCode.SUCCESS) {
            Res101702 res101702 = new Res101702();
            res101702.setIsSuccess(true);
            res101702.setCode(code);
            log.addOperateLog("101702", JSON.toJSONString(req), "获取验证码", "手机号码：" + phone + "获取验证码成功，验证码：" + code,
                LogOperateEnum.LOG_OTHER.getCode(), LogStatusEnum.SUCCESS.getCode(), startLogTime);
            return Result.success(req, res101702);
        } else {
            log.addOperateLog("101702", JSON.toJSONString(req), "获取验证码",
                "手机号码：" + phone + "获取验证码失败：" + bizCodeEnum.getMessage(), LogOperateEnum.LOG_OTHER.getCode(),
                LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, bizCodeEnum);
        }
    }

    @RequestMapping(value = "/101703", method = RequestMethod.POST)
    @ApiOperation(value = "用户登录", notes = "用户登录")
    @ResponseBody
    public Result<Res101703> login(@RequestBody GatewayRequest<Req101703> req) throws Exception {
        log.debug(req, "login {}  ", "begin");
        long startLogTime = System.currentTimeMillis();
        LoginRevertInfo loginRevertInfo = null;
        try {
            ValidationUtils.validateEntityStr(req.getContent());
            loginRevertInfo = loginService.login(req);
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            log.addLoginLog("101703", JSON.toJSONString(req), "用户登录", log.buildErrmsg(e),
                LogOperateEnum.LOG_OTHER.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, e.getMessage());
        }
        log.debug(req, "login {} ", "end");
        if (loginRevertInfo.getUserInfo() != null) {
            ThreadLocalScope.setAuthData(loginRevertInfo.getUserInfo().getId());
        }
        if (loginRevertInfo.getBizCodeEnum() == BizCode.SUCCESS) {
            log.addLoginLog("101703", JSON.toJSONString(req), "用户登录",
                loginRevertInfo.getUserInfo().getUsername() + "登录成功", LogOperateEnum.LOG_OTHER.getCode(),
                LogStatusEnum.SUCCESS.getCode(), startLogTime);
            return Result.success(req, loginRevertInfo.getRes101703());
        } else {
            String userName="";
            if(StringUtils.isNotBlank(req.getContent().getUserName())){
                userName=req.getContent().getUserName()+"  ";
            }
            log.addLoginLog("101703", JSON.toJSONString(req), userName+"用户登录", loginRevertInfo.getBizCodeEnum().getMessage(),
                LogOperateEnum.LOG_OTHER.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, loginRevertInfo.getBizCodeEnum());
        }
    }

    @RequestMapping(value = "/101704", method = RequestMethod.POST)
    @ApiOperation(value = "用户菜单列表", notes = "用户菜单列表")
    @ResponseBody
    public Result<Res101704> getUserPermission(@RequestBody GatewayRequest<Req101704> req) {
        log.debug(req, "getUserPermission {}  ", "begin");
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        Res101704 res101704 = null;
        try {
            String userId = ThreadLocalScope.getAuthData().getUser();
            String platformCode = ThreadLocalScope.getAuthData().getAppId();
            if (userId != null) {
                List<SysPermissionTree> list = sysUserService.getSysPermissionTreeByUserId(userId, platformCode);
                PermissionDataUtil.addIndexPage(list);
                res101704 = new Res101704();
                res101704.setList(list);
                bizCodeEnum = BizCode.SUCCESS;
            } else {
                bizCodeEnum = BizCode.NOT_USER;
            }
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            return Result.error(req, e.getMessage());
        }
        log.debug(req, "getUserPermission {}  ", "end");
        if (bizCodeEnum == BizCode.SUCCESS) {
            return Result.success(req, res101704);
        } else {
            return Result.error(req, bizCodeEnum);
        }
    }

    @RequestMapping(value = "/101705", method = RequestMethod.POST)
    @ApiOperation(value = "校验菜单权限编码", notes = "校验菜单权限编码")
    @ResponseBody
    public Result<Res101705> checkPermissionsByperms(@RequestBody GatewayRequest<Req101705> req) {
        log.debug(req, "checkPermissionsByperms {}  ", "begin");
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        Res101705 res101705 = null;
        try {
            String userId = ThreadLocalScope.getAuthData().getUser();
            ValidationUtils.validateEntityStr(req.getContent());
            res101705 = new Res101705();
            if (userId != null) {
                boolean ok = sysUserService.checkPermissionsByperms(req.getContent().getPerms(), userId);
                if (ok) {
                    res101705.setIsSuccess(true);
                    res101705.setMessage(BizCode.SUCCESS.getMessage());
                } else {
                    res101705.setIsSuccess(false);
                    res101705.setMessage(BizCode.NOt_METHOD_AUTHORITY.getMessage());
                }
                bizCodeEnum = BizCode.SUCCESS;
            } else {
                throw new ValidationException(BizCode.NOT_USER.getCode());
            }
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            return Result.error(req, e.getMessage());
        }
        log.debug(req, "checkPermissionsByperms {}  ", "end");
        if (bizCodeEnum == BizCode.SUCCESS) {
            return Result.success(req, res101705);
        } else {
            return Result.error(req, bizCodeEnum);
        }
    }

}
